package net.aiion.weave.impl.ui.xhtml;

import net.aiion.weave.spi.xml.XmlContext;
import net.aiion.weave.spi.xml.XmlEventFactory;
import net.aiion.weave.spi.xml.XmlSink;
import net.aiion.weave.spi.xml.events.CharactersXmlEvent;
import net.aiion.weave.spi.xml.events.XmlEvent;

public class XhtmlWhitespaceTransformer implements XmlSink
{
    public XhtmlWhitespaceTransformer() {
    }

    @Override
    public void handleXmlEvent(final XmlContext aXmlContext) {
        final XmlEvent xmlEvent = aXmlContext.getXmlEvent();
        switch (xmlEvent.getType()) {
        case XmlEvent.CHARACTERS:
            transformCharacters(aXmlContext, (CharactersXmlEvent) xmlEvent);
            break;
        default:
            aXmlContext.forwardEvent();
            break;
        }
    }

    private void transformCharacters(final XmlContext aXmlContext, final CharactersXmlEvent aXmlCharacters) {
        if (aXmlCharacters.isWhitespace() && aXmlCharacters.getData().length() > 0) {
            return;
        }

        final String trimmedData = aXmlCharacters.getData().trim();
        if (trimmedData.length() < aXmlCharacters.getData().length()) {
            aXmlContext.forwardXmlEvent(XmlEventFactory.getInstance().createCharacters(trimmedData));
            return;
        }

        aXmlContext.forwardEvent();
    }
}
